<template>
    <el-form label-width="80px" size="normal">
        <el-form-item label="SPU名称">
            <el-input placeholder="SPU名称" v-model="spuInfo.spuName"></el-input>
        </el-form-item>
        <el-form-item label="品牌">
            <el-select placeholder="请选择" v-model="(spuInfo.tmId as number)">
                <el-option v-for="trademark in trademarkList" :key="trademark.id" :value="trademark.id" :label="trademark.tmName"></el-option>
            </el-select>
        </el-form-item>
        <el-form-item label="SPU描述">
            <el-input type="textarea" placeholder="SPU描述" rows="4" v-model="spuInfo.description"></el-input>
        </el-form-item>
        <el-form-item label="SPU图片">
            <el-upload v-model:file-list="spuImageList as UploadUserFile[]"
                :action="`${baseUrl}/admin/product/upload`" list-type="picture-card"
                :on-preview="handlePictureCardPreview" :on-remove="handleRemove">
                <el-icon>
                    <Plus />
                </el-icon>
            </el-upload>
            <el-dialog v-model="dialogVisible">
                <img w-full :src="dialogImageUrl" alt="Preview Image" />
            </el-dialog>
        </el-form-item>
        <el-form-item label="销售属性">
            <el-select :placeholder="`还有${unUseSaleAttr.length}个未选择`" v-model="tempAttr">
                <el-option v-for="item in unUseSaleAttr" :key="(item.id as number)" :value="`${item.id}:${item.name}`" :label="item.name">
                </el-option>
            </el-select>
            <el-button type="primary" size="default" @click="addSaleAttr" :disabled="!tempAttr">添加销售属性</el-button>
        </el-form-item>
        <el-form-item>
            <el-table border stripe :data="nowSaleAttr">
                <el-table-column type="index" width="80" label="序号"/>
                <el-table-column label="属性名" prop="saleAttrName"></el-table-column>
                <el-table-column label="属性值名称列表">
                    <template #='{row}'>
                        <el-tag
                            v-for="(tag,index) in row.spuSaleAttrValueList"
                            :key="tag.id"
                            closable
                            :disable-transitions="false"
                            @close="row.spuSaleAttrValueList.splice(index,1)"
                            >
                            {{tag.saleAttrValueName}}
                        </el-tag>
                        <el-input
                            class="input-new-tag"
                            size="small"
                            v-if="row.isEdit"
                            ref="inpEle"
                            v-model="row.inputValue"
                            @blur="changeToLook(row)"
                        >
                        </el-input>
                        <el-button class="button-new-tag" size="small" v-else @click="changeToEdit(row)">+ 新增属性值</el-button>
                    </template>
                </el-table-column>
                <el-table-column label="操作">
                    <template v-slot="{ row ,$index}">
                    <el-button
                    type="danger"
                    size="small"
                    @click="nowSaleAttr.splice($index,1)"
                    icon="ele-Delete"
                    ></el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-form-item>
        <el-form-item>
            <el-button type="primary" size="default" @click="save">保存</el-button>
            <el-button type="default" size="default" @click="emit('setState',0)">取消</el-button>
        </el-form-item>
    </el-form>

</template>

<script lang="ts">
import { defineComponent } from "vue";

export default defineComponent({
    name: "SpuForm",
});
</script>

<script setup lang="ts">
import { ref , onMounted,computed, nextTick} from 'vue'
import { Plus } from '@element-plus/icons-vue'
import { ElMessage, type UploadProps, type UploadUserFile } from 'element-plus'
import { requestBaseSaleAttrList,requestSpuSaleAttrList, requestSpuImgList, type BaseSaleAttrListType,
 type SpuImgListType, type SpuInfoType, type SpuSaleAttrListType, type SpuSaleAttrItemType, requestUpdateSpuInfo, requestSaveSpuInfo } from '@/api/spu'
import { requestAllTrademark, type reqTrademarkReturnRecordsType } from '@/api/trademark';

//照片墙
// const fileList = ref<UploadUserFile[]>([
//     {
//         name: 'food.jpeg',
//         url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100',
//     }
// ])
//上传图片请求前缀
const baseUrl = import.meta.env.VITE_API_URL
const dialogImageUrl = ref('')
const dialogVisible = ref(false)

const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
    console.log(uploadFile, uploadFiles)
}

const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
    dialogImageUrl.value = uploadFile.url!
    dialogVisible.value = true
}

//接收传过来的spuInfo
const props = defineProps<{
    spuInfo: SpuInfoType
}>()
//接收自定义事件
const emit = defineEmits<{
    (event: 'setState', state: number): void
}>()

//定义4个初始值，品牌列表，图片列表，销售属性列表，当前销售属性列表
const trademarkList = ref<reqTrademarkReturnRecordsType>([])
const spuImageList = ref<SpuImgListType>([])
const allSaleAttr = ref<BaseSaleAttrListType>([])
const nowSaleAttr = ref<SpuSaleAttrListType>([])

//定义一个函数发送初始请求
const getAllUseData = async () => {
    //判断有无id，知道是修改还是添加
    if(!props.spuInfo.id){
        try{
            //请求品牌列表
          const re = await requestAllTrademark()
          trademarkList.value = re
          //请求销售属性列表
          const re1 = await requestBaseSaleAttrList()
          allSaleAttr.value = re1
        }catch(e){
            ElMessage.error('品牌请求或者属性列表请求失败')
        }
    }else{
        //所有需要的请求一起发
        //请求品牌列表
        const req1 = requestAllTrademark()
        //请求销售属性列表
        const req2 = requestBaseSaleAttrList()
        //请求图片列表
        const req3 = requestSpuImgList(props.spuInfo.id)
        //请求当前销售属性列表
        const req4 = requestSpuSaleAttrList(props.spuInfo.id)
        try{
            const result = await Promise.all([req1,req2,req3,req4])
            trademarkList.value = result[0]
            allSaleAttr.value = result[1]
            spuImageList.value = result[2]
            //照片墙需要name，和url，给图片列表添加属性
            spuImageList.value.forEach(item => {
                item.name = item.imgName
                item.url = item.imgUrl
            })
            nowSaleAttr.value = result[3]
            //在当前属性列表的每一项属性中添加一个isEdit属性控制是否有input编辑
            //添加一个inputValue获取用户输入的属性值
            nowSaleAttr.value.forEach(item => {
                item.isEdit = false
                item.inputValue = ''
            })
        }catch(e){
            ElMessage.error('初始请求失败')
        }
    }
}
//初始化请求
onMounted(() => {
    getAllUseData()
})

//计算属性计算未选择的销售属性
const unUseSaleAttr = computed(() => {
    //删除销售属性已经在下面列表展示的
    return allSaleAttr.value.filter(item1 => {
        return  nowSaleAttr.value.every(item2 => {
            return item2.saleAttrName !== item1.name
        })
    })
})

//定义临时属性，保存用户选中的销售属性
const tempAttr = ref('')

//点击添加销售属性
const addSaleAttr = () => {
    //定义一个新的销售属性
    const newSaleAttr = ref<SpuSaleAttrItemType>({
        baseSaleAttrId: +tempAttr.value.split(':')[0],
        saleAttrName: tempAttr.value.split(':')[1],
        spuSaleAttrValueList: []
    })
    nowSaleAttr.value.push(newSaleAttr.value)
    //清除用户临时信息
    tempAttr.value = ''
}
//定义一个ref，获取input元素
const inpEle = ref()
//点击新增属性值，显示input编辑
const changeToEdit = (row:SpuSaleAttrItemType) => {
    row.isEdit = true
    //自动获取焦点
    nextTick(() => {
        inpEle.value.focus()
    })
}
//失去焦点,变成查看模式
const changeToLook = (row:SpuSaleAttrItemType) => {
    //获取用户输入属性值
    let inpValue = row.inputValue as string
    //判断用户输入是否为空
    if(!inpValue.trim()){
        //关闭input框
        row.isEdit = false
        return
    }
    //判断是否重复
    const isReset = row.spuSaleAttrValueList.some(item => {
        return item.saleAttrValueName === inpValue
    })
    //如果重复
    if(isReset){
        //关闭input框
        row.isEdit = false
        //清空输入的属性值
        row.inputValue = ''
        return
    }
    //定义一个新的属性值
    const newSaleAttrValue = {
        baseSaleAttrId: row.baseSaleAttrId,
        saleAttrValueName: row.inputValue as string
    }
    //添加到当前属性的属性值列表中
    row.spuSaleAttrValueList.push(newSaleAttrValue)
    //清空输入的属性值，关闭输入框
    row.inputValue = ''
    row.isEdit = false
}

//点击保存，发送修改或者添加请求
const save = async () => {
    //整理需要的图片列表
    const newImageList = spuImageList.value.map((item) => {
        //新上传的图片地址在response里面
        if(item.response){
            return {
                imgName: item.name as string,
                imgUrl: item.response.data
            }
        }else{
            return {
                imgName: item.imgName,
                imgUrl: item.imgUrl
            }
        }
    })
    //整理需要的销售属性列表,删除多余的属性
    nowSaleAttr.value.map(item => {
        delete item.isEdit
        delete item.inputValue
    })
    
    //赋值给需要上传的spuInfo
    props.spuInfo.spuImageList = newImageList
    props.spuInfo.spuSaleAttrList = nowSaleAttr.value
    try {
        //判断有无id,有就是修改
        if(props.spuInfo.id){
            await requestUpdateSpuInfo(props.spuInfo)  
            ElMessage.success('修改成功') 
        }else{
            await requestSaveSpuInfo(props.spuInfo)
            ElMessage.success('添加成功') 
        }
        //回到分页列表
        emit('setState',0)
    } catch (e) {
        ElMessage.error('修改或者添加失败')
    }
}
</script>